<?php
namespace api\controllers;

//use yii\web\Controller;
use common\models\Active;
use common\models\ActiveAttr;
//use common\models\Activity;
//use common\models\ActivityAttr;
use common\models\Goods;
use common\models\Group;
use common\models\Order;
use common\models\Service;
use common\models\Shop;
use common\service\CommonService;
use common\service\ConstantService;
use common\service\GroupService;
use common\service\WechatService;
use yii\base\Module;
use common\models\GoogsAttr;
class PayController extends BaseController
{

    public function __construct($id, Module $module, array $config = [])
    {
        parent::__construct($id, $module, $config);
    }


    /**
     * 去支付
     */
    public function actionPayOrder(){
        if($this->isGet()) {
            $order_id = $this->get('order_id');
            $order = Order::find()->where(['id' => $order_id])->asArray()->one();

            //先去查该用户和该活动的最后一次参加的团,判断团是否有效 有一个状态值,如果有效则说明该团里面没有他
            // 这个地方有问题 事先添加订单的订单后面才支付 会导致同一个团可以参加多次  需要在多加一个条件 顺序的问题
            if($order['order_type'] == 1){
                $user_order = Order::find()
                    ->where(['user_id'=>$order['user_id'],'order_type'=>1,'active_id'=>$order['active_id']])
                    ->orderBy(['created_time'=>SORT_DESC])
                    ->asArray()
                    ->one();
                if(!empty($user_order)){
                    $group = Group::find()->where(['id'=>$user_order['group_id']])->asArray()->one();
                    if($group['status'] == 2){//该团在有效期内
                        return $this->renderJson([],'不能重复参与当前团',ConstantService::$response_fail);
                    }
                }
            }
            $openid = $this->user['openid'];
            $active = Active::find()->where(['id'=>$order['active_id']])->asArray()->one();
            $title = $active['active_name'];
            $out_trade_no = $order['order_no'];
            $total = round($order['order_money'] * 100,2);
            $res = WechatService::createUnifiedOrder($openid, $title, $out_trade_no, $total);
            if($res === false){
                return $this->renderJson([],'错误',ConstantService::$response_fail);

            }
            return $this->renderJson($res,'成功',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);

    }




    /**
     * 支付成功回调
     */
    public function actionPaySuccess(){
        $param = file_get_contents('php://input');

        $result = CommonService::xmlToArray($param);
        // 查询订单.
        if(CommonService::checkSign($result)){
//        $result['out_trade_no'] = 'shop201808075b696e2ae0deb';
//        $result['transaction_id'] = 'shop201808075b696e2ae0deb';
            $order = Order::findOne(['order_no'=>$result['out_trade_no']]);
            if($order['pay_status'] == ConstantService::$pay_status['PAY_SUCCESS']){
                exit('success');
            }
            //修改支付状态为成功　修改订单状态为拼团中
            $order->pay_status = ConstantService::$pay_status['PAY_SUCCESS'];
            $order->serial_no = $result['transaction_id'];
            $order->pay_time = time();
            if($order['order_type'] == 2){
                //
                $order->order_status = ConstantService::$order_status['WAIT_DELIVER'];
            }else{
                $order->order_status = ConstantService::$order_status['GROUPING'];
            }

            $order->save() && $this->_reduceStock($order['goods_attr_id'],$order['goods_num']);
            //添加服务记录费用
            $this->_addService($order);

            if($this->_addDisplaySales($order) === false){
                exit('error');
            }

            if($order['order_type'] == 2)
            {
                exit('success');
            }

            $group_id = $this->_addGroup($order);

            if($group_id === false){
                exit('error');
            }
            if(GroupService::chectGroupStatus($group_id) === true){
                //团满了　批量修改为代发货
                $arr = [
                    'order_status' => ConstantService::$order_status['WAIT_DELIVER'],
                    ];
                //修改团为有效团
                $current_group = Group::findOne(['id'=>$group_id]);
                $current_group->status = 1;
                $current_group->complete_time = time();
                $current_group->save();
                if(Order::updateAll($arr,['group_id'=>$group_id])){
                    exit('success');
                }
            }
            exit('success');

        }
        exit('error');
    }
    /**
     * 减库存量
     */
    private function _reduceStock($id,$inventory){
        if(empty($id)){
            return false;
        }
        $current_attr = ActiveAttr::findOne(['id'=>$id]);
        if(!$current_attr){
            return false;
        }

        if($current_attr['inventory'] < 0){
            return false;
        }
        $current_attr->inventory = $current_attr['inventory']-$inventory;

        if($current_attr->save(false)){
            return true;
        }
        return false;
    }


    /**
     * 入库成团表
     * @param array $order
     * @return  bool|integer
     */
    private function _addGroup($order){
        //判断是否满员 重新写入group表　
        $current_group = Group::find()
            ->where(['active_id' => $order['active_id'],'status'=>2])
            ->orderBy(['id' => SORT_DESC])
            ->one();

        if(empty($current_group)){
            //没有团的时候
            $surplus = 0;
        }else{
            $surplus = $current_group['group_num'] - $current_group['current_group_num'];
        }
//        $surplus = $current_group['group_num'] - $current_group['current_group_num'];
        if (!$surplus) {
            //这里需要改之前的订单状态为代发货
            //需要新增新团
            $group_model = new Group();
            $active = Active::findOne(['id' => $order['active_id']]);
            $group_row['launch_id'] = $order['user_id'];
            $group_row['active_id'] = $order['active_id'];
            $group_row['goods_id'] = $order['goods_id'];
            $group_row['shop_id'] = $order['shop_id'];
            $group_row['group_num'] = $active['active_num'];
            $group_row['status'] = 2; //在有效期内
            $group_row['current_group_num'] = 1;
            $group_row['create_time'] = time();
            $group_row['update_time'] = time();
            $group_row['expire_time'] = time() + 60 * 60 * 24;
            $group_model->setAttributes($group_row);
            if (!($group_model->save())) {
                return false;
            }


            $group_id = \Yii::$app->db->getLastInsertID();
        } else {
            //往之前团里面加
            $group_id = $current_group['id'];
            //修改成团数量表
            if ($surplus) {
                $current_group->current_group_num = $current_group['current_group_num'] + 1;
                $current_group->update_time = time();
                $current_group->save();
            }
        }
        $order->group_id = $group_id;
        if($order->save()){
            return $group_id;
        }
        return false;
    }

    /**
     * 设置交易服务费用
     * @param $order
     * @return bool
     */
    private function _addService($order){
        $data = [];
        $data['order_id'] = $order['id'];
        $data['user_id'] = $order['user_id'];
        $data['shop_id'] = $order['shop_id'];
        $data['order_money'] = $order['order_money'];
        $service_money =round($order['order_money'] * 0.006,2);
        $data['service_money'] = $service_money;
        $data['create_time'] = time();

        $query = new Service();
        $query->setAttributes($data);

        if($query->save()){
            $shop = Shop::findOne(['id'=>$order['shop_id']]);
            $shop->service_money = sprintf("%.2f",($shop['service_money'] ? $shop['service_money']:0) + $service_money);
            $shop->save();
            return true;
        }
        return false;

    }


    /**
     * 新增成团数量
     * @param $order
     */
    private function _addDisplaySales($order){
        //修改属性
        $activeAttr = ActiveAttr::findOne(['id' => $order['goods_attr_id']]);
        $activeAttr->display_sales = $activeAttr['display_sales'] + $order['goods_num'];

        //修改活动
        $active = Active::findOne(['id'=>$order['active_id']]);
        $active->display_sales = $active['display_sales'] + $order['goods_num'];
        if($activeAttr->save() && $active->save()){
            return true;
        }
        return false;

    }





}